<template>
  <div>
    <div class="inquireheader">
      <div class="ihleft">
        <img :src="params.product.img" alt="" class="ihleftImg">
      </div>
      <div class="ihright">
        <h2>{{params.product.name}}</h2>
        <p>零售价：¥ {{params.product.price}}</p>
        <p>防伪码：{{params.code}}</p>
      </div>
    </div>

    <div class="inquirecontent">
      <p>绑定身份信息,享受更多增值服务</p>

      <div>
        <span>姓名</span>
        <input type="text" placeholder="请输入正确的姓名" v-model="name">
      </div>
      <div>
        <span>手机</span>
        <input type="number" placeholder="请输入正确的手机号" v-model="phone" oninput="if(value.length>11)value=value.slice(0,11)">
      </div>

      <!-- 原地址 -->
      <!-- <div style="position:relative;">
        <span>地址</span>
        <b class="dizhi">
          <demo @getaddress="getAddress"></demo>
        </b>
        <input type="text" v-model="address" placeholder="请选择地址">
        <img src="../../assets/images/right_small.png" alt="" class="arrows">
      </div> -->

      <!-- 新地址 -->
      <div class="adressBox choice">
        <yd-cell-group class="ydddd">
          <yd-cell-item arrow>
            <span slot="left">地区</span>
            <input slot="right" type="text" style="font-size:.373333rem;color:#000;" @click.stop="show1 = true" v-model="address" readonly placeholder="请选择收货地址">
          </yd-cell-item>
        </yd-cell-group>
        <yd-cityselect v-model="show1" :callback="result1" :items="district"></yd-cityselect>
      </div>

      <div class="addr">
        <span>详细地址</span>
        <!-- <input type="text" placeholder="街道/楼号/门牌号" v-model="detaileAddress"> -->
        <textarea class="ipt-addr" maxlength="50" placeholder="街道/楼号/门牌号" v-model="detaileAddress"></textarea>
      </div>

      <div class="upd" style="position: relative;">
        <p>发票/小票</p>
        <p v-if="src != ''" class="invoice" :style="bacSrc" style="margin-top: 12px;"></p>
        <span v-else style="float:left;">
          点击上传产品购买时的发票/小票或网站订单截图，支持JPG/JPEG/PNG，5M以内
          <input type="file" @change="getimg" class="fileImg" accept="image/*">
        </span>
        <div class="closeBtn" @click="hideImg" v-show="src">
          <img src="../../assets/images/delete_result-fapiao.png" alt="">
        </div>
      </div>

      <button @click="checkbd" :class="{'checkbtn': btnStatus}">立即绑定</button>
    </div>

    <div class="inquirefoot">
      <p>相关说明</p>
      <span>填写该信息仅用于投诉、建议、举报后便于我司联系您核实情况，或在售后按照上述联系方式和地址进行投递。我司承诺不泄露您包括联系方式在内的任何信息。</span>
    </div>
    <div class="cover" v-show="coversuccess">
      <div class="hint">
        <p>恭喜！绑定成功</p>
        <span>您可享受更多增值服务</span>
        <div class="check" @click="checkprocuct">查看我的产品</div>
      </div>
    </div>

    <div class="popup" v-show="showHints">已被绑定</div>
    <div class="popup" v-show="checkEmpty">{{errorMsg}}</div>
    <div class="popup" v-show="lessthan">请上传小于5M的图片</div>
    <toast :type="type" v-show="load">{{msg}}</toast>
  </div>
</template>

<script>
import demo from "./demo";
import District from "ydui-district/dist/gov_province_city_area_id";
import toast from "../loading/loading";

export default {
  components: {
    demo,
    toast
  },

  data() {
    return {
      show1: false,
      address: "",
      district: District,
      params: this.$route.query,
      pattern: new RegExp(
        "[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]"
      ),
      phoneReg: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
      name: "",
      phone: "",
      checkname: true,
      detaileAddress: "",
      src: "",
      params: this.$route.query,
      coversuccess: false,
      userId: "",
      showHints: false,
      checkEmpty: false,
      lessthan: false,
      errorMsg: "请填写完整",
      msg: "绑定中",
      type: "loading",
      load: false
    };
  },
  mounted() {
    var cookie = document.cookie.split(";");
    var cookies = [];
    for (var i = 0; i < cookie.length; i++) {
      var temp = cookie[i].trim().split("=");
      cookies[temp[0]] = temp[1];
    }
    var id = cookies["id"];
    if (!id) {
      window.location.href = "http://wztest.wofew.com/api/Main/login";
    } else {
      this.userId = id;
      this.getUserInfo();
    }

    //初始化textarea自动换行
    this.autoTextarea(document.getElementsByClassName("ipt-addr")[0], 0, 100);
  },
  computed: {
    btnStatus() {
      return Boolean(
        this.name &&
          this.phone &&
          this.address &&
          this.detaileAddress &&
          this.src
      );
    },
    bacSrc() {
      if (this.src) {
        return {
          background: "url(" + this.src + ") no-repeat center center",
          backgroundSize: "100%"
        };
      }
    },
    getphone() {
      return this.phoneReg.test(this.phone);
    }
  },
  methods: {
    result1(ret) {
      this.address = ret.itemName1 + "/" + ret.itemName2 + "/" + ret.itemName3;
    },
    autoTextarea: function(elem, extra, maxHeight) {
      extra = extra || 0;
      var isFirefox = !!document.getBoxObjectFor || "mozInnerScreenX" in window,
        isOpera = !!window.opera && !!window.opera.toString().indexOf("Opera"),
        addEvent = function(type, callback) {
          elem.addEventListener
            ? elem.addEventListener(type, callback, false)
            : elem.attachEvent("on" + type, callback);
        },
        getStyle = elem.currentStyle
          ? function(name) {
              var val = elem.currentStyle[name];

              if (name === "height" && val.search(/px/i) !== 1) {
                var rect = elem.getBoundingClientRect();
                return (
                  rect.bottom -
                  rect.top -
                  parseFloat(getStyle("paddingTop")) -
                  parseFloat(getStyle("paddingBottom")) +
                  "px"
                );
              }

              return val;
            }
          : function(name) {
              return getComputedStyle(elem, null)[name];
            },
        // minHeight = parseFloat(getStyle("height"));
        minHeight = 20;

      elem.style.resize = "none";

      var change = function() {
        var scrollTop,
          height,
          padding = 0,
          style = elem.style;

        if (elem._length === elem.value.length) return;
        elem._length = elem.value.length;

        if (!isFirefox && !isOpera) {
          padding =
            parseInt(getStyle("paddingTop")) +
            parseInt(getStyle("paddingBottom"));
        }
        scrollTop =
          document.body.scrollTop || document.documentElement.scrollTop;

        elem.style.height = minHeight + "px";
        if (elem.scrollHeight > minHeight) {
          if (maxHeight && elem.scrollHeight > maxHeight) {
            height = maxHeight - padding;
            style.overflowY = "auto";
          } else {
            height = elem.scrollHeight - padding;
            style.overflowY = "hidden";
          }
          style.height = height + extra + "px";
          scrollTop += parseInt(style.height) - elem.currHeight;
          document.body.scrollTop = scrollTop;
          document.documentElement.scrollTop = scrollTop;
          elem.currHeight = parseInt(style.height);
        }
      };

      addEvent("propertychange", change);
      addEvent("input", change);
      addEvent("focus", change);
      change();
    },
    checkbd() {
      var that = this;
      if (!this.getphone) {
        this.errorMsg = "手机格式有误";
        this.checkEmpty = true;
        setTimeout(() => {
          this.checkEmpty = false;
        }, 2000);
        return;
      }
      if (!this.btnStatus) {
        this.errorMsg = "请填写完整";
        this.checkEmpty = true;
        setTimeout(() => {
          this.checkEmpty = false;
        }, 2000);
        return;
      }
      this.load = true;
      var data = {
        id: this.params.userId,
        product_id: this.params.productid,
        code: this.params.code,
        name: this.name,
        phone: this.phone,
        address: this.address,
        detailaddress: this.detaileAddress,
        img: this.src,
        img_s: ""
      };
      $.ajax({
        type: "post",
        data: data,
        url: `${this.$store.state.globalIp}/api/Main/product_bind`,
        dataType: "json",
        success(result) {
          that.load = false;
          if (result.message == "成功") {
            that.coversuccess = true;
          } else if (result.message == "已经绑定") {
            that.showHints = true;
            setTimeout(() => {
              this.showHints = false;
              that.$router.go(-1);
            }, 2000);
          }
        }
      });
    },
    checkprocuct() {
      var that = this;
      $.ajax({
        type: "get",
        data: {
          user_id: ""
        },
        url: `${this.$store.state.globalIp}/api/Main/bind_list`,
        dataType: "json",
        success(result) {
          if (result.message) {
            that.$router.replace("product");
          }
        }
      });
    },
    getUserInfo() {
      var data = {
        user_id: this.userId
      };
      var that = this;
      $.ajax({
        type: "get",
        data: data,
        url: `${this.$store.state.globalIp}/api/Main/user_msg`,
        dataType: "json",
        success(result) {
          console.log(result);
          if (result.message == "成功") {
            that.name = result.data.name;
            that.phone = result.data.phone;
            that.address = result.data.address;
            that.detaileAddress = result.data.detailaddress;
          }
        }
      });
    },

    getAddress(data) {
      this.address = data;
    },
    getimg() {
      this.src = "";
      var file = document.querySelector("input[type=file]").files[0];
      if (file.size > 5 * 1024 * 1024) {
        this.errorMsg = "图片大小不能大于5M";
        this.checkEmpty = true;
        setTimeout(() => {
          this.checkEmpty = false;
        }, 2000);
        return;
      }
      console.log(file.type);
      if (
        !(
          file.type == "image/jpeg" ||
          file.type == "image/jpg" ||
          file.type == "image/png"
        )
      ) {
        this.errorMsg = "仅支持jpg或png格式的图片";
        this.checkEmpty = true;
        setTimeout(() => {
          this.checkEmpty = false;
        }, 2000);
        return;
      }
      var reader = new FileReader();
      var that = this;
      reader.addEventListener(
        "load",
        function() {
          that.src = reader.result;
        },
        false
      );

      if (file) {
        reader.readAsDataURL(file);
      }
    },
    hideImg() {
      this.src = "";
    }
  }
};
</script>

<style>
.weui_toast {
  z-index: 999;
}
.inquirecontent .yd-cell-item input {
  padding-left: 0;
}
.inquirecontent > div.adressBox {
  height: 44px;
  overflow: hidden;
}
.choice.adressBox {
  margin: 12px 0 0 0;
}
#app > div > .adressBox {
  margin: 12px 0 0 0;
}
.ydddd {
  width: 100%;
  height: 44px;
}
#app div.inquirecontent > div.addr {
  display: flex;
  align-items: flex-start;
  justify-content: flex-start;
  height: auto;
}
.addr .ipt-addr {
  flex: 1;
  min-height: 20px;
  max-height: 60px;
  border: none;
  resize: none;
  font-size: 14px;
  margin-top: 10px;
  margin-bottom: 10px;
  line-height: 1.5;
}
.inquireheader {
  width: 351px;
  height: 124px;
  background: rgba(255, 255, 255, 1);
  border-radius: 5px;
  margin: 22px auto;
  padding: 12px;
  box-sizing: border-box;
}
.ihleft {
  width: 100px;
  height: 100px;
  /* background: pink; */
  float: left;
}
.ihleftImg {
  width: 100px;
  height: 100px;
  /* background: pink; */
  float: left;
}
.ihright {
  width: 220px;
  height: 100px;
  float: right;
  padding-left: 12px;
  box-sizing: border-box;
}
.ihright h2 {
  font-size: 18px;
  font-family: PingFangSC-Medium;
  color: rgba(51, 51, 51, 1);
  line-height: 50px;
}
.ihright p {
  font-size: 14px;
  font-family: PingFangSC-Regular;
  color: rgba(51, 51, 51, 1);
  line-height: 20px;
  margin-top: 2px;
}
.inquirecontent {
  width: 351px;
  height: auto;
  background: rgba(255, 255, 255, 1);
  border-radius: 5px;
  margin: 0 auto;
  padding: 15px;
  box-sizing: border-box;
}
.inquirecontent p {
  font-size: 14px;
  font-family: PingFangSC-Regular;
  color: rgba(255, 93, 32, 1);
  line-height: 20px;
}
.inquirecontent > div:not(.upd) {
  /* width:327px; */
  height: 44px;
  border-radius: 5px;
  border: 1px solid rgba(0, 0, 0, 1);
  margin: 12px auto;
  line-height: 44px;
  padding: 0 10px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
}

.yd-cell .yd-cell-item {
  padding: 0;
}
.adressBox .yd-cell-box {
  margin-bottom: 0;
}

.inquirecontent div span {
  font-size: 14px;
  font-family: PingFangSC-Regular;
  color: rgba(51, 51, 51, 1);
  margin-right: 10px;
}

.inquirecontent div input:not([placeholder="请选择收货地址"]) {
  flex: 1;
  border: none;
  outline: none;
  font-size: 14px;
  width: 230px;
  /* height: 42px;
  line-height: 42px; */
  color: #000;
  padding-bottom: 3px;
}
.inquirecontent div.upd {
  /* width: 327px; */
  height: 156px;
  border-radius: 5px;
  border: 1px solid rgba(0, 0, 0, 1);
  padding: 10px;
  box-sizing: border-box;
}
.inquirecontent div.upd p {
  font-size: 14px;
  font-family: PingFangSC-Regular;
  color: rgba(51, 51, 51, 1);
}
.inquirecontent div.upd span {
  width: 80%;
  height: 60%;
  font-size: 14px;
  margin: 20px 40px;
  line-height: 20px;
  color: #999;
  position: relative;
}
.inquirecontent div input.fileImg {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  opacity: 0;
}
.inquirecontent button {
  width: 327px;
  height: 44px;
  background: rgba(187, 187, 187, 1);
  border-radius: 5px;
  color: #fff;
  font-size: 18px;
  font-family: PingFangSC-Regular;
  text-align: center;
  line-height: 44px;
  outline: none;
  border: none;
  margin-top: 10px;
  background-color: #000;
}
.inquirefoot {
  width: 327px;
  height: 79px;
  /* margin: 24px auto 50px; */
  margin: 24px 24px 34px 24px;
}
.inquirefoot p {
  font-size: 14px;
  font-family: PingFangSC-Regular;
  color: rgba(51, 51, 51, 1);
  line-height: 20px;
}

.inquirefoot span {
  display: block;
  font-size: 12px;
  font-family: PingFangSC-Regular;
  color: rgba(153, 153, 153, 1);
  line-height: 20px;
  margin-top: 8px;
}
.cover {
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.4);
  position: fixed;
  left: 0;
  top: 0;
  z-index: 5;
}
.hint {
  width: 281px;
  height: 146px;
  background: rgba(255, 255, 255, 1);
  border-radius: 8px;
  margin-top: 212px;
  margin-left: 48px;
}
.hint p {
  font-size: 18px;
  font-family: STHeitiSC-Light;
  color: rgba(0, 0, 0, 1);
  line-height: 19px;
  padding-top: 25px;
  margin-left: 78px;
}
.hint span {
  font-size: 15px;
  font-family: STHeitiSC-Light;
  color: rgba(154, 154, 154, 1);
  line-height: 15px;
  display: block;
  margin-left: 65px;
  padding-top: 15px;
}
.check {
  width: 281px;
  height: 45px;
  font-size: 18px;
  font-family: STHeitiSC-Light;
  color: rgba(0, 194, 0, 1);
  line-height: 45px;
  text-align: center;
  margin-top: 16px;
  border-radius: 0px 0px 8px 8px;
  border-top: 1px solid rgba(210, 211, 213, 1);
}
.arrows {
  display: inline-block;
  width: 8px;
  height: 14px;
  margin-top: 12px;
  margin-left: 15px;
}
.dizhi div {
  border: none;
  position: absolute;
  top: -14px;
  left: 40px;
}
.invoice {
  display: inline-block;
  width: 303px;
  height: 100px;
  background-size: 100%;
}
.inquirecontent div.closeBtn {
  position: absolute;
  right: 12px;
  top: 1rem;
  width: 23px;
  height: 23px;
  margin: 0;
  padding: 0;
  border: none;
  /* z-index: 99; */
}
.checkbtn {
  background: #000 !important;
  color: #fff !important;
}
.inputAll {
  color: #333 !important;
}
.popup {
  width: 245px;
  height: 44px;
  background: rgba(40,40,40,.75);
  border-radius: 5px;
  font-size: 16px;
  font-family: PingFangSC-Regular;
  color: rgba(255, 255, 255, 1);
  line-height: 44px;
  text-align: center;
  /* margin: 0 auto; */
  position: fixed;
  left: 68px;
  top: 280px;
}
</style>

